<!--
 * @company : 版权所属 四川北星惯牌科技有限公司
 * @contact : 刘经理 19326416371
 -->
<template>
	<view class="initiateTeam-box">
		<!-- 赛制填写 -->
		<view class="from-system">
			<text class="name">组队信息填写</text>
			<view class="from-box">
				<view class="from-item flex-row-center">
					<text class="from-name">组队名称</text>
					<up-input border="none" placeholderClass="placeholderClass" fontSize="26rpx" color="#DEDEDE"
						placeholder="请输入内容" v-model="teamInfo.name"></up-input>
				</view>
				<view class="from-item flex-row-center">
					<text class="from-name">时间范围</text>
					<view class="example-body flex-row-center">
						<view class="example-item" @click="datetimeStartShow=true">
							<up-input inputAlign="right" border="none" disabled placeholderClass="placeholderClass"
								fontSize="26rpx" color="#DEDEDE" placeholder="请选择开始时间"
								v-model="teamInfo.startTime"></up-input>
						</view>
						<text class="example-icon">-</text>
						<view class="example-item" @click="datetimeEndShow=true">
							<up-input border="none" disabled placeholderClass="placeholderClass" fontSize="26rpx"
								color="#DEDEDE" placeholder="请选择结束时间" v-model="teamInfo.endTime"></up-input>
						</view>
					</view>
				</view>
				<!-- 				<view class="from-item flex-row-center">
					<text class="from-name">参与费用</text>
					<view class="from-item-right flex-row-center" @click="priceFocus">
						<up-input disabled border="none" placeholderClass="placeholderClass" fontSize="26rpx"
							color="#DEDEDE" placeholder="请输入内容" type="digit" v-model="teamInfo.price">
							<template #suffix>
								<text class="price-icon">元</text>
							</template>
						</up-input>
					</view>
				</view> -->
				<view class="from-item flex-row-center">
					<text class="from-name">参与人数</text>
					<up-number-box min="2" step="2" v-model="teamInfo.peopleNum">
						<template #minus>
							<view class="minus-btn flex-center">
								<up-icon name="minus" color="#0B2532" size="24rpx"></up-icon>
							</view>
						</template>
						<template #input>
							<up-input type="number" v-model="teamInfo.peopleNum" fontSize="28rpx" inputAlign="center"
								color="#fff" border="none" :customStyle="{width:'120rpx'}"></up-input>
							<!-- <text class="input-num">{{teamInfo.peopleNum}}</text> -->
						</template>
						<template #plus>
							<view class="plus-btn flex-center">
								<up-icon name="plus" color="#102C38" size="24rpx"></up-icon>
							</view>
						</template>
					</up-number-box>
				</view>
				<!-- =========门店身份提交======= -->
				<template v-if="storeAddInfo.id">
					<view class="from-item flex-row-center">
						<text class="from-name">组队门店</text>
						<view class="from-item-right flex-row-center">
							<up-input border="none" disabled placeholderClass="placeholderClass" fontSize="26rpx"
								color="#DEDEDE" placeholder="请输入内容" v-model="storeAddInfo.storeName"></up-input>
						</view>
					</view>
				</template>
				<!-- =========用户身份提交======= -->
				<template v-else>
					<view class="from-item flex-row-center">
						<text class="from-name">是否全额支付</text>
						<view class="from-item-right flex-row-center">
							<up-radio-group placement="row" v-model="teamInfo.type">
								<up-radio activeColor="#8BDEB7" :customStyle="{}" label="是" :name="1"> </up-radio>
								<up-radio activeColor="#8BDEB7" :customStyle="{marginLeft:'18rpx'}" label="否" :name="0">
								</up-radio>
							</up-radio-group>
						</view>
					</view>
					<view class="from-item flex-row-center">
						<text class="from-name">选择门店</text>
						<view class="from-item-right flex-row-center">
							<up-radio-group placement="row" v-model="teamInfo.status">
								<up-radio activeColor="#8BDEB7" :customStyle="{}" label="是" :name="1"> </up-radio>
								<up-radio activeColor="#8BDEB7" :customStyle="{marginLeft:'18rpx'}" label="否" :name="0">
								</up-radio>
							</up-radio-group>
						</view>
					</view>
					<view class="from-item flex-row-center" v-if="teamInfo.status===1">
						<text class="from-name">组队门店</text>
						<view class="from-item-right flex-row-center" @click="storeShow=true">
							<up-input border="none" disabled placeholderClass="placeholderClass" fontSize="26rpx"
								inputAlign="right" color="#DEDEDE" placeholder="请输入内容"
								v-model="teamInfo.storeName"></up-input>
							<up-icon name="arrow-right" color="#5B6868" size="28rpx"></up-icon>
						</view>
					</view>
					<view class="from-item flex-row-center" v-else>
						<text class="from-name">地址填写</text>
						<up-input border="none" disabled placeholderClass="placeholderClass" fontSize="26rpx"
							color="#DEDEDE" placeholder="请输入内容" v-model="teamInfo.address">
							<template #suffix>
								<up-icon @click="chooseLocationTap" name="map-fill" color="#DEDEDE"
									size="42rpx"></up-icon>
							</template>
						</up-input>
					</view>
				</template>
				<!-- 助教 -->
				<view class="w100" style="margin-top: 60rpx;">
					<chooseAssistantVue :startDate="teamInfo.startTime" :endDate="teamInfo.endTime"
						@changeAssistant="changeAssistants" :assistantIds="teamInfo.assistantId">
					</chooseAssistantVue>
				</view>
			</view>
		</view>
		<!-- 组队描述 -->
		<view class="from-system">
			<!-- style="margin-bottom: 32rpx	;" -->
			<text class="name">组队描述</text>
			<!-- 占位 -->
			<view style="height: 26rpx;"></view>
			<view class="from-box">
				<up-textarea border="none" placeholderClass="placeholderClass" v-model="teamInfo.description" class=""
					placeholder="请输入内容" count></up-textarea>
				<!-- 上传图片 -->
				<view style="margin-top: 24rpx;">
					<up-upload @delete="deletePic" :fileList="fileList" @afterRead="afterRead" name="1" multiple
						:maxCount="9" width="200rpx" height="200rpx">
						<view class="upload-box flex-center">
							<up-icon name="camera" color="#999999" size="70rpx"></up-icon>
							<text class='text'>添加照片</text>
						</view>
					</up-upload>
				</view>
			</view>
		</view>
		<!-- 须知信息 -->
		<view class="notice-box flex">
			<text class="name">须知信息</text>
			<text class="details">{{teamInfo.notice}} </text>
		</view>
		<!-- 提交按钮 -->
		<view class="submit-box flex-center">
			<up-button text="立即组队" @click="submitClick" :loading="teamInfo.loading" loadingText="提交中"
				:customStyle="{'color':'#115B56'}"
				color="linear-gradient( 270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%)" shape="circle"></up-button>
		</view>
		<!-- 时间选择组件 -->
		<up-datetime-picker :minDate="nowTime" @cancel="datetimeStartShow=false" v-model="nowTime"
			:formatter="formatter" title="组队开始时间" :show="datetimeStartShow" @confirm="confirmStartTime"
			mode="datetime"></up-datetime-picker>
		<up-datetime-picker :formatter="formatter" title="组队结束时间" :minDate="nowTime" @cancel="datetimeEndShow=false"
			v-model="nowTime" :show="datetimeEndShow" @confirm="confirmEndTime" mode="datetime"></up-datetime-picker>
		<!-- 价钱输入键盘 -->
		<up-keyboard ref="uKeyboard" mode="number" tips="输入参加金额" @confirm="confirmKeyboard" @cancel="cancelKeyboard"
			@change="valChange" @backspace="backspace" :overlay="false" :show="keyboardShow"></up-keyboard>
		<!-- 选择门店弹窗 -->
		<up-popup :show="storeShow" @close="closeStoreShow" round="18rpx" closeable>
			<choseStroe :storeId="teamInfo.storeId" :storeShow="storeShow" @confirm="chooseStore"></choseStroe>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		formatDate,
		countDecimalPlaces,
		toDecimal2
	} from '@/utils/utools.js';
	import chooseAssistantVue from '@/components/assistant/chooseAssistant.vue';
	import {
		test
	} from '@/uni_modules/uview-plus';
	import {
		chooseLocation
	} from '@/utils/chooseLocation';
	import {
		userInfoStore
	} from '@/stores/user';
	import choseStroe from '@/page_user/components/choseStore.vue';
	import {
		configInfoStore
	} from '@/stores/config';
	const {
		configInfo
	} = configInfoStore();

	const rules = {
		name: {
			required: true,
			msg: '请填写队伍名称'
		},
		startTime: {
			required: true,
			msg: '请选择组队开始时间'
		},
		endTime: {
			required: true,
			msg: '请选择组队结束时间'
		},
		peopleNum: {
			required: true,
			msg: '请填写组队人数'
		}
	};
	const keyboardShow = ref(false);
	const userStore = userInfoStore();
	const fileList = ref([]);
	const storeShow = ref(false);
	const nowTime = Date.now(); //当前时间
	const datetimeStartShow = ref(false);
	const datetimeEndShow = ref(false);
	const storeAddInfo = reactive({ //门店身份发起组队
		id: 0,
		storeName: ''
	})
	const teamInfo = reactive({
		name: '', //组队名称
		startTime: '',
		startTimestamp: '', //开始时间搓
		endTimestamp: '', //结束时间搓
		endTime: '',
		peopleNum: 4,
		status: 1, //是否选择门店
		storeId: '',
		storeName: '',
		description: '', //描述
		loading: false,
		address: '',
		lat: '',
		lon: '',
		type: 0, //金额全款 0 AA 1 全额
		assistantId: '',
		notice: computed(() => configInfo.team_notice.value), //组队须知
	});
	const storeId = ref('');
	onLoad((option) => {
		if (option.storeId) { //是否商家发布
			// console.log('商家发布组队', option);
			storeAddInfo.id = option.storeId;
			storeAddInfo.storeName = option.storeName;
		}
	})
	const chooseStore = (item) => { //选择门店
		teamInfo.storeName = item.store_name;
		teamInfo.storeId = item.id;
		storeShow.value = false;
	}
	const changeAssistants = (list) => { //选择助教
		teamInfo.assistantId = list;
	}
	const closeStoreShow = () => { //关闭选择门店弹窗
		storeShow.value = false;
	}
	const chooseLocationTap = async () => { //选择地理位置
		uni.showLoading({
			title: '加载中'
		})
		chooseLocation('', '', true).then((res) => {
			uni.hideLoading();
			if (res) {
				teamInfo.address = res.address + (res.name ? res.name : '');
				teamInfo.lat = res.latitude;
				teamInfo.lon = res.longitude;
			}
		}).catch(() => {
			uni.hideLoading();
			uni.$u.toast('获取位置失败');
		})
	}
	const confirmStartTime = (e) => { //选择开始时间
		if (e.value) {
			if (teamInfo.endTimestamp && teamInfo.endTimestamp <= e.value) {
				uni.$u.toast('请选择小于组队的结束时间');
				return
			}
			teamInfo.startTimestamp = e.value;
			teamInfo.startTime = formatDate(e.value, 'yyyy-MM-dd hh:mm');
			datetimeStartShow.value = false;
		}
	}
	const confirmEndTime = (e) => { //选择结束时间
		if (e.value) {
			if (teamInfo.startTimestamp && teamInfo.startTimestamp >= e.value) {
				uni.$u.toast('请选择大于组队的开始时间');
				return
			}
			teamInfo.endTimestamp = e.value;
			teamInfo.endTime = formatDate(e.value, 'yyyy-MM-dd hh:mm');
			datetimeEndShow.value = false;
		}
	}
	const priceFocus = () => { //聚焦
		keyboardShow.value = true;
	}
	const confirmKeyboard = () => { //确认参加金额
		if (!test.amount(teamInfo.price)) {
			uni.$u.toast('请输入正确的金额');
			return
		}
		keyboardShow.value = false;
	}
	const cancelKeyboard = () => { //取消填写金额
		teamInfo.price = toDecimal2(teamInfo.price)
		keyboardShow.value = false;
	}
	const valChange = (val) => {
		if (val == '.' && teamInfo.price.includes('.')) return
		if (countDecimalPlaces(teamInfo.price) >= 2) return
		teamInfo.price += val;
	};
	const backspace = () => { // 删除价钱的最后一个字符
		if (teamInfo.price.length) {
			teamInfo.price = teamInfo.price.substr(0, teamInfo.price.length - 1);
		}
	};
	const deletePic = (event) => { // 删除图片
		fileList.value.splice(event.index, 1);
	};
	const afterRead = async (event) => { //上传图片
		let lists = [].concat(event.file);
		let fileListLen = fileList.value.length;
		lists.map((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await $Api.uploadFile.uploadFilePromise(lists[i].url);
			if (result.code == '1') {
				let item = fileList.value[fileListLen];
				fileList.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result.data.fullurl,
				});
			} else {
				let item = fileList.value[fileListLen];
				fileList.value.splice(fileListLen, 1, {
					...item,
					status: 'failed',
					message: '上传失败',
				});
			}
			fileListLen++;
		}
	}
	const submitClick = () => { //提交按钮
		if (storeAddInfo.id) { //门店身份
			submitStoreTeam();
		} else {
			submitTeam()
		}
	}
	const getcheckAssistant = async (ids) => {
		return new Promise(async (resolve, reject) => {
			const res = await $Api.assistant.checkAssistant({
				assistant_ids: teamInfo.assistantId,
				numbers: teamInfo.peopleNum,
				start_time: teamInfo.startTime,
				end_time: teamInfo.endTime,
			})
			if (res.code == 1) {
				resolve({
					assistantType: 1
				})
			} else {
				resolve({
					assistantType: -1
				})
				uni.$u.toast(res.msg);
			}
		})
	}
	const submitTeam = async () => { //提交信息
		if (teamInfo.loading) return
		const validate = validateForm(teamInfo, rules); //验证
		if (!validate.status) return
		if (teamInfo.status === 1) { //门店
			if (!teamInfo.storeId) {
				uni.$u.toast('请选择组队门店')
				return
			}
		} else {
			if (!teamInfo.address) {
				uni.$u.toast('请选择组队地址')
				return
			}
		}

		let imageList = []
		fileList.value.forEach(val => {
			if (val.status == 'success') {
				imageList.push(val.url)
			}
		})
		if (imageList.length == 0) {
			uni.$u.toast('请上传组队图片')
			return
		}
		const imageStr = imageList.join(',');
		if (teamInfo.assistantId) { // 检查助教
			const {
				assistantType
			} = await getcheckAssistant();
			if (assistantType == -1) return;
		}

		teamInfo.loading = true;
		const res = await $Api.group.submitGroup({
			title: teamInfo.name,
			is_store: teamInfo.status,
			store_id: teamInfo.storeId,
			address: teamInfo.address,
			start_date: teamInfo.startTime,
			end_date: teamInfo.endTime,
			number_people: teamInfo.peopleNum,
			describe: teamInfo.description,
			long: teamInfo.lon,
			lat: teamInfo.lat,
			image: imageStr,
			assistantId: teamInfo.assistantId,
			type: teamInfo.type,
		})
		if (res.code == 1) {
			uni.showToast({
				title: '提交成功'
			})
			setTimeout(() => {
				teamInfo.loading = false;
				uni.redirectTo({
					url: '/page_main/views/paymentTeam?id=' + res.data.id
				})

			}, 800)
		} else {
			teamInfo.loading = false;
			uni.$u.toast(res.msg);
		}
	}
	const submitStoreTeam = async () => { //门店身份提交组队
		if (teamInfo.loading) return
		const validate = validateForm(teamInfo, rules); //验证
		if (!validate.status) return
		let imageList = []
		fileList.value.forEach(val => {
			if (val.status == 'success') {
				imageList.push(val.url)
			}
		})
		if (imageList.length == 0) {
			uni.$u.toast('请上传组队图片')
			return
		}
		const imageStr = imageList.join(',');
		if (teamInfo.assistantId) { // 检查助教
			const {
				assistantType
			} = await getcheckAssistant();
			if (assistantType == -1) return;
		}
		teamInfo.loading = true;
		const res = await $Api.group.submitStoreGroup({
			title: teamInfo.name,
			store_id: storeAddInfo.id,
			start_date: teamInfo.startTime,
			end_date: teamInfo.endTime,
			number_people: teamInfo.peopleNum,
			describe: teamInfo.description,
			assistantId: teamInfo.assistantId,
			is_store: 1,
			image: imageStr
		})
		if (res.code == 1) {
			uni.showToast({
				title: '提交成功'
			})
			setTimeout(() => {
				teamInfo.loading = false;
				uni.navigateBack();
			}, 800)
		} else {
			teamInfo.loading = false;
			uni.$u.toast(res.msg);
		}
	}
	const formatter = (type, value) => {
		if (type === 'year') {
			return `${value}年`;
		}
		if (type === 'month') {
			return `${value}月`;
		}
		if (type === 'day') {
			return `${value}日`;
		}
		if (type === 'hour') {
			return `${value}时`;
		}
		if (type === 'minute') {
			return `${value}分`;
		}
		return value;
	};
</script>
<style lang="scss">
	.u-search__content__input {
		background: transparent !important;
	}
</style>
<style lang="scss" scoped>
	.initiateTeam-box {
		padding: 20rpx;
		box-sizing: border-box;
		width: 100%;
	}

	.from-system {
		padding: 40rpx 28rpx;
		box-sizing: border-box;
		width: 100%;
		border-radius: 20rpx;
		background-color: #222528;
		margin-bottom: 32rpx;

		.name {
			font-weight: bold;
			font-size: 30rpx;
			color: #E2E3E3;
		}

		.marB {
			margin-bottom: 28rpx;
		}
	}

	.from-box {
		width: 100%;

		.from-item {
			box-sizing: border-box;
			width: 100%;
			margin-top: 60rpx;

			// &:not(:last-child) {
			// 	margin-top: 32rpx;
			// }
			::v-deep.placeholderClass {
				color: #5B6868 !important;
				font-size: 26rpx;
				font-weight: 500;
			}

			.from-name {
				display: block;
				font-weight: 500;
				font-size: 28rpx;
				color: #FFFFFF;
				margin-right: 38rpx;
			}

			.from-item-right {
				flex: 1;
			}

			.up-textarea-box {
				color: #fff;
			}
		}

		.price-icon {
			font-weight: 500;
			font-size: 28rpx;
			color: #C2C3C4;
		}

		.minus-btn {
			width: 34rpx;
			height: 34rpx;
			background: #A7A8A9;
			border-radius: 4rpx;
		}

		.input-num {
			width: 64rpx;
			font-weight: 500;
			font-size: 28rpx;
			color: #fff;
			text-align: center;
		}

		.plus-btn {
			width: 34rpx;
			height: 34rpx;
			background: linear-gradient(270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%);
			box-shadow: 0rpx 4rpx 6rpx 0rpx rgba(108, 199, 190, 0.38);
			border-radius: 4rpx;
		}

		.example-body {
			flex: 1;

			.example-icon {
				font-size: 28rpx;
				color: #fff;
				margin: 0 24rpx;
			}
		}
	}

	.notice-box {
		flex-direction: column;
		margin-top: 16rpx;

		.name {
			font-weight: 500;
			font-size: 28rpx;
			color: #A2A3A4;
			line-height: 33rpx;
		}

		.details {
			font-weight: 500;
			font-size: 26rpx;
			color: #585A5C;
			line-height: 30rpx;
			margin-top: 16rpx;
		}
	}

	.upload-box {
		width: 200rpx;
		height: 200rpx;
		border-radius: 8rpx;
		background-color: #36393B;
		flex-direction: column;

		.text {
			font-weight: 500;
			font-size: 24rpx;
			margin-top: 16rpx;
			color: rgba(255, 255, 255, 0.3);
		}
	}

	.submit-box {
		width: 336rpx;
		height: 84rpx;
		margin: 48rpx auto;
	}
</style>
<style>
	.u-textarea__count,
	.u-input,
	.u-textarea {
		padding: 0 !important;
		background-color: transparent !important;
	}

	.placeholderClass {
		color: #5B6868 !important;
		font-size: 26rpx;
		font-weight: 500;
	}

	.u-textarea__field {
		color: #fff !important;
	}
</style>